package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-10-07
 * Time: 17:20
 */
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;
    public UdpEchoClient(String serverIp , int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        socket = new DatagramSocket();//传入参数为请求的目的ip和目的端口，源ip为本机ip源端口为系统分配的端口


    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.print("->");
            if (!scanner.hasNext()){//如果没有输入的话就结束循环
                break;
            }
            String request = scanner.next();//人为输入请求
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);//指定服务器的ip和端口，分开的
            socket.send(requestPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096] , 4096);
            socket.receive(responsePacket);
            //转化为字符串
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());//内置getLength()获取length成员变量
            System.out.println(response);



        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
